let axios = require('axios')
let statusCode = require('../config/statusCode')
let { open, pull } = global.config.auth

module.exports = app => {
  if (open) {
    axios.get(pull).then(res => {
      let { code, data } = res.data
      if (code == statusCode.SUCCESS.code) {
        app.context.ruleMap = data
      }
    })
    app.use(async (ctx, next) => {
      let path = ctx.path
      let roles = ctx.ruleMap[path]
      let userRoles = ctx.tokenInfo.roles.map(i => parseInt(i))
      if (!roles) {
        await next()
      } else {
        roles = roles.map(i => parseInt(i))
        if (new Set(roles.concat(userRoles)).size >= roles.length + userRoles.length) {
          ctx.stop('NO_POWER')
        } else {
          await next()
        }
      }
    })
  }
}